package pl.olsson.plugin.script;

import java.io.Reader;

/**
 *
 * @author nilols
 */
public class ProxyReader extends Reader {

    private Reader defaultReader;
    private Reader currentReader;

    public ProxyReader(Reader reader) {
        defaultReader = reader;
    }

    public void setReader(Reader reader) {
        if (null != currentReader) {
            try {
                currentReader.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        currentReader = reader;
    }

    protected Reader getReader() {
        return (null!=currentReader?currentReader:defaultReader);
    }

    @Override
    public int read(char[] chars, int i, int i1) {
        try {
            return getReader().read(chars, i, i1);
        } catch (Exception e) {
                throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
        if (null != currentReader) {
            try {
                currentReader.close();
                currentReader = null;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
